<template>
	<div class="diy-box">
		<el-card shadow="never" class="!border-none flex-1" :body-style="{ height: '100%' }">
			<el-form class="mt-4" label-width="90px">
				<el-form-item label="主题颜色：">
					<div
						class="style-item cursor-pointer"
						:class="{ active: formData.identify === item.identify }"
						v-for="(item, index) in styleData"
						:key="item.identify"
						@click="setStyle(index, item)"
					>
						<span class="color" :style="{ backgroundColor: item.color }"></span>
						<span class="text">{{ item.name }}</span>
					</div>
				</el-form-item>
				<el-form-item label="示例图片：">
					<div class="img-box">
						<el-image v-if="activeImageUrl" class="w-[100%] h-[100%]" :src="getUrl(activeImageUrl)" lazy />
					</div>
				</el-form-item>
			</el-form>
		</el-card>
		<footerSubmit>
			<el-button v-auth="'diy/setStyleData'" type="primary" @click="handleSubmit">保存</el-button>
		</footerSubmit>
	</div>
</template>

<script setup lang="ts" name="decorationStyle">
import { reactive, ref, onMounted } from 'vue';
import { diyGetStyle, diySetStyle } from '/@/api/diy';
import { getUrl } from '/@/utils/util';
import { messageSuccess } from '/@/utils/message';

const styleData = ref([]);

const activeImageUrl = ref('');

const formData = reactive({
	index: 0,
	name: '',
	color: '',
	identify: '',
});

const setStyle = (index: number, item: any) => {
	for (const key in formData) {
		if (item[key] != null && item[key] != undefined) {
			formData[key] = item[key];
		}
	}
	formData.index = index;
	activeImageUrl.value = styleData.value[index].image_url;
};

const getData = async () => {
	const data = await diyGetStyle({ type: 1 });
	if (data?.info) styleData.value = data.info;
	if (data.data) {
		for (const key in formData) {
			if (data.data[key] != null && data.data[key] != undefined) {
				formData[key] = data.data[key];
			}
		}
	}
	activeImageUrl.value = styleData.value[formData.index].image_url;
};

// 保存提交
const handleSubmit = async () => {
	await diySetStyle({ type: 1, data: formData });
	getData();
	messageSuccess('设置成功');
};

onMounted(() => {
	getData();
});
</script>

<style scoped lang="scss">
.diy-box {
	.style-item {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20px;
		margin-bottom: 10px;
		width: 120px;
		height: 50px;
		color: #666666;
		border: 1px solid #dcdee2;
		border-radius: 4px;
		text-align: center;
		line-height: 40px;
		.color {
			margin-right: 10px;
			width: 20px;
			height: 20px;
			border: 0;
			border-radius: 3px;
		}
	}

	.style-item.active {
		border-color: var(--el-color-primary);
		background: #f9f9f9;
	}

	.image-box {
		width: 800px;
		height: 100%;
		padding: 15px;
		border-radius: 6px;
		box-sizing: border-box;
		background: #f8f8f8;
	}
}
</style>
